package com.tianci.appstore.controller.manager;

import android.os.Environment;
import android.os.RemoteException;
import android.os.StatFs;

import com.coocaa.x.framework.app.CoocaaApplication;
import com.coocaa.x.framework.utils.LiteURI;
import com.coocaa.x.framework.utils.LogUtils;
import com.coocaa.x.service.XServiceManager;
import com.coocaa.x.service.litecontent.LiteContentServiceConnecter;
import com.coocaa.x.service.litecontent.data.apps.com_coocaa_app.AppData;
import com.coocaa.x.service.litecontent.data.apps.com_coocaa_app.RP_Installed_Apps;
import com.coocaa.x.service.litepm.aidl.ILitePMInstallListener;
import com.coocaa.x.service.litepm.aidl.ILitePMUninstallListener;
import com.coocaa.x.service.litepm.data.AppInfo;
import com.coocaa.x.service.litepm.data.InstallParams;
import com.skyworth.framework.skysdk.util.SdCardChecker;
import com.tianci.appstore.controller.AppStoreBaseController;
import com.tianci.appstore.ui.data.SkyListAppData;
import com.tianci.appstore.ui.data.SkyListAppData.ListType;
import com.tianci.appstore.ui.list.uninstall.UninstallListDataListener;
import com.tianci.appstore.utils.ExternalStorageMonitor;
import com.tianci.appstore.utils.ExternalStorageMonitor.ExternalStorageMonitorListener;
import com.tianci.appstore.utils.SkyConstants;
import com.tianci.appstore.utils.Tools;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class DeleteManagerController extends AppStoreBaseController implements
        ExternalStorageMonitorListener {

    private static DeleteManagerController managerController = null;
    private UninstallListDataListener mListener = null;
    private List<SkyListAppData> installedList = null;
    private List<SkyListAppData> waitUninstallList = null;
    private boolean continueUninstall = false;
    private List<SkyListAppData> needUninstallList = null;
    // private int needUninstallSize = 0;
    private int uninstalledSize = 0;
    private boolean isSilent = false;
    private float lastSize = 0;

    public static DeleteManagerController getInstance() {
        if (null == managerController)
            managerController = new DeleteManagerController();
        return managerController;
    }

    public DeleteManagerController() {
        // InstalledReceiver.addListener(this);
        installedList = new ArrayList<SkyListAppData>();
        waitUninstallList = new ArrayList<SkyListAppData>();

    }

    public void init() {
        runOnThread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                try {
                    isSilent = !CoocaaApplication.installWithPackageInstaller();
                    XServiceManager.getLitePMService().addUninstallListener(appPMstub);
                    XServiceManager.getLitePMService().addInstallListener(appInstallStub);
                    // LiteAppApplication
                    ExternalStorageMonitor.setListener(DeleteManagerController.this);
                } catch (RemoteException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
    }

    public void setUninstallListDataListener(UninstallListDataListener listener) {
        mListener = listener;
    }

    public int getWaitUninstallList() {
//        for(SkyListAppData app:waitUninstallList){
//            LogUtils.d("","sunny resume app:"+app.getPkgName());
//        }
        return waitUninstallList.size();
    }

    public int getInstalledeAppCount() {
        if (installedList != null) {
            return installedList.size();
        }
        return 0;
    }

    public float getInstalledAppSize() {
        if (installedList != null && installedList.size() > 0) {
            float allSize = 0;
            long size = 0;
            for (int i = 0; i < installedList.size(); i++) {
                long appSize = installedList.get(i).getSize();
                size += appSize;
                allSize = (float) size / SkyConstants.KTOM;
                allSize = Tools.fixFloat(allSize);
            }
            return allSize;
        } else {
            return (float) 0.0;
        }
    }


    private List<SkyListAppData> formData(List<AppInfo> list) {
        List<SkyListAppData> ret = new ArrayList<SkyListAppData>();
        for (AppInfo info : list) {
            SkyListAppData appInfo = new SkyListAppData(ListType.LOCAL_APP_LIST, "", info.appName,
                    "", info.pkgName);
            appInfo.setVersionName(String.valueOf(info.versionCode));
            appInfo.setMainActivity(info.mainActivity);
            long size = info.size / SkyConstants.BTOK;
            appInfo.setSize(size);
            float size2 = (float) size / SkyConstants.KTOM;
            if (size2 > 1.0f) {
                size2 = Tools.fixFloat(size2);
                appInfo.setShowInfo(String.valueOf(size2) + "MB");
            } else {
                appInfo.setShowInfo(String.valueOf(size) + "KB");
            }
            ret.add(appInfo);
        }
        return ret;
    }

    public List<SkyListAppData> getInstalledList() {
        // installedList = AppDataProvider.getInstance().getLocalData().getInstalledAllApp();
        LiteURI uri = LiteURI.create("apps://com.coocaa.app/installed_apps");
        uri.addParams("filter", "delete");
        String json = null;
        try {
            json = LiteContentServiceConnecter.getService().call(uri.toString());
        } catch (RemoteException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        List<AppInfo> appinfos = new ArrayList<AppInfo>();
        if (json != null) {
            RP_Installed_Apps rp = RP_Installed_Apps.parseJObject(json, RP_Installed_Apps.class);
            List<AppData> appdatas = rp.resource.resource_items;
            if (appdatas != null && appdatas.size() > 0) {
                for (AppData appdata : appdatas)
                    appinfos.add(appdata.info);
            }
        }

        installedList = formData(appinfos);
        LogUtils.d("localapp", "getInstalledList   size:" + installedList.size());
        return installedList;
    }

    // 获取系统总内存
    public float getTotalInternalMemorySize() {
        File path = Environment.getDataDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSize();
        long totalBlocks = stat.getBlockCount();
        float size = (float) (totalBlocks * blockSize) / SkyConstants.BTOM;
        size = Tools.fixFloat(size);
        return size;
    }

    // 获取系统可用的总内存
    public float getAvailableInternalMemorySize() {
        File path = Environment.getDataDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSize();
        long availableBlocks = stat.getAvailableBlocks();
        float size = (float) (availableBlocks * blockSize) / SkyConstants.BTOM;
        size = Tools.fixFloat(size);
        return size;
    }

    private boolean isSDCardAvaiable() {
        boolean isSDExit = SdCardChecker.isSDCardAvaiable();
        if (isSDExit) {
            boolean isSDEmulated = Environment.isExternalStorageEmulated();
            if (!isSDEmulated)
                return true;
        }
        return false;
    }

    public float getSDcardAvailableSpace() {
        float size = 0;
        try {
            size = SdCardChecker.getSDCardAvailableStore() / SkyConstants.BTOM;
            lastSize = size;
        } catch (Exception e) {
            size = lastSize;
            e.printStackTrace();
        }
        return size;
    }

    public synchronized void refreshDeleteManagerList(List<SkyListAppData> selectList) {
        if (mListener == null) {
            return;
        }
        mListener.onUninstallListLoaded(getInstalledList(), selectList);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                LogUtils.d("install", "refreshDeleteManagerList  size:" + getAvailableInternalMemorySize());
                if (isSDCardAvaiable()) {
                    if (mListener != null)
                        mListener.onUpdateCountAndSize(getAvailableInternalMemorySize(),
                                getSDcardAvailableSpace());
                } else {
                    if (mListener != null)
                        mListener.onUpdateCountAndSize(getAvailableInternalMemorySize(), -1);
                }
            }
        }).start();
    }

    public void uninstallApp(String pkg) {
        // LogUtils.d("intent", "uninstallAppList..."+pkg);
        try {
            XServiceManager.getLitePMService().uninstall(pkg, isSilent);
        } catch (RemoteException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


    public void uninstallAppList(List<SkyListAppData> list) {
//        LogUtils.d("un", "uninstall uninstallAppList..." + list.size());
        if (list == null || list.size() < 1) {
            return;
        }
//        synchronized (waitUninstallList) {
//            waitUninstallList = null;
//            waitUninstallList = new ArrayList<SkyListAppData>();
//            waitUninstallList.addAll(list);
//            uninstallApp(list.get(0).getPkgName(), list.get(0).getTitle());
//        }
        List<String> pkgList = new ArrayList<String>();
        for(SkyListAppData data:list)
            pkgList.add(data.getPkgName());
        LogUtils.d("un", "CONTROLLER  uninstall uninstallAppList... " + pkgList.size());
        try {
            XServiceManager.getLitePMService().uninstallApps(pkgList,true);
        } catch (RemoteException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public List<String> getUninstallList()
    {
        List<String> list = null;
        try {
            list = XServiceManager.getLitePMService().getUninstallList();
        } catch (RemoteException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return list;
    }

    @Override
        public void destroy() {
        // TODO Auto-generated method stub
        runOnThread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                try {
                    XServiceManager.getLitePMService().removeInstallListener(appInstallStub);
                    XServiceManager.getLitePMService().removeUninstallListener(appPMstub);
                    ExternalStorageMonitor.clearListener(DeleteManagerController.this);
                } catch (RemoteException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
        mListener = new UninstallListDataListener() {
            @Override
            public void onUpdateCountAndSize(float internalSize, float externalSize) {

            }

            @Override
            public void onUninstallListLoaded(List<SkyListAppData> dataList, List<SkyListAppData> selectedList) {

            }

            @Override
            public void onUninstallStart(String pkg) {

            }

            @Override
            public void onUninstallFinished(int success, String pkg) {

            }

        };
    }


    private ILitePMInstallListener.Stub appInstallStub = new ILitePMInstallListener.Stub() {

        @Override
        public void onInstallStart(String arg0, AppInfo appInfo, final InstallParams params) throws RemoteException {

        }

        @Override
        public void onInstallEnd(String arg0, AppInfo appInfo, int arg2, String arg3, final InstallParams params)
                throws RemoteException {
            getInstalledList();
            refreshDeleteManagerList(null);
        }
    };

    private ILitePMUninstallListener.Stub appPMstub = new ILitePMUninstallListener.Stub() {

        @Override
        public void onUninstallStart(final AppInfo appInfo) throws RemoteException {
            LogUtils.d("un", "CONTROLLER onUninstallStart  pkg:" + appInfo.pkgName);
            mListener.onUninstallStart(appInfo.pkgName);
        }

        @Override
        public synchronized void onUninstallEnd(final AppInfo appInfo, final int success, String extra)
                throws RemoteException {
            LogUtils.d("un", "CONTROLLER  onUninstallEnd  pkg:" + appInfo.pkgName + " success:" + success);
            if (success == 0) {
                getInstalledList();
            }
            if (isSilent) {
                if (success != 0) {
                    LogUtils.d("un", "CONTROLLER  onUninstallEnd failed  ... pkg:" + appInfo.pkgName);
                    mListener.onUninstallFinished(-1, appInfo.pkgName);
                } else {
                    LogUtils.d("un", "CONTROLLER  onUninstallEnd success  ... pkg:" + appInfo.pkgName);
                    mListener.onUninstallFinished(0, appInfo.pkgName);
                    refreshDeleteManagerList(null);
                }
//
            } else {
                if (success == 0) {
                    refreshDeleteManagerList(null);
                    mListener.onUninstallFinished(0, null);
                } else {
                    mListener.onUninstallFinished(-1, null);
                }
            }
//            synchronized (waitUninstallList) {
//                LogUtils.d("intent", "onUninstallEnd---continueUninstall:" + continueUninstall + " "
//                        + waitUninstallList.size());
//                if (success == 0) {
//                    // deleteApp(pkgname);
//                    getInstalledList();
//                }
//                if (isSilent) {
//                    if (success != 0) {
//                        LogUtils.d("intent", "onUninstallEnd---uninstall failed");
//                        mListener.onUninstallFinished(uninstalledSize, null);
//                    } else {
//                        if (waitUninstallList != null && waitUninstallList.size() > 0) {
//                            uninstalledSize++;
//                            waitUninstallList.remove(0);
//                            if (waitUninstallList.size() == 0) {
//                                LogUtils.d("intent", "onUninstallEnd--finish----");
//                                mListener.onUninstallFinished(uninstalledSize, null);
//                                uninstalledSize = 0;
//                            } else {
//                                uninstallAppList(waitUninstallList);
//                            }
//                        } else {
//                            mListener.onUninstallFinished(uninstalledSize, null);
//                        }
//                    }
//                    refreshDeleteManagerList(waitUninstallList);
//                } else {
//                    if (success == 0) {
//                        refreshDeleteManagerList(null);
//                        mListener.onUninstallFinished(1, null);
//                    } else {
//                        mListener.onUninstallFinished(-1, null);
//                    }
//                }
//            }
        }
    };

    @Override
    public void onExternalStorageChanged(boolean bMounted) {
        // TODO Auto-generated method stub
        refreshDeleteManagerList(null); // 换到pmlistener中回调
    }

}
